package com.fog.student.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fog.student.common.Base;
import com.fog.student.common.UserContext;
import com.fog.student.entity.Admin;
import com.fog.student.entity.Student;
import com.fog.student.entity.Teacher;
import com.fog.student.entity.User;
import com.fog.student.service.AdminService;
import com.fog.student.service.StudentService;
import com.fog.student.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private StudentService studentService;
    @Resource
    private TeacherService teacherService;

    @PostMapping("/user/login")
    public Base login(HttpServletRequest request,@RequestBody User user){

        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username",user.getUsername()));
        Student student = studentService.getOne(new QueryWrapper<Student>().eq("username",user.getUsername()));
        Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("username",user.getUsername()));

        if(admin!=null){
            if (admin.getPassword().equals(user.getPassword())){
                user.setId(admin.getId());
                request.getSession().setAttribute("admin",user.getId());
                UserContext.setUserId(user.getId());
                return Base.success("admin");
            }
        }
        if(student!=null){
            if (student.getPassword().equals(user.getPassword())){
                user.setId((long)student.getId());
                request.getSession().setAttribute("student", user);
                UserContext.setUserId(user.getId());
                return Base.success("student");
            }
        }
        if(teacher!=null){
            if (teacher.getPassword().equals(user.getPassword())){
                user.setId((long)teacher.getId());
                request.getSession().setAttribute("teacher", user);
                UserContext.setUserId(user.getId());
                return Base.success("teacher");
            }
        }
        return Base.error("失败");
    }

    @PostMapping("user/logout")
    public Base logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return Base.success(null);
    }


}
